package com.cakeshop.servelt;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.cakeshop.model.User;
import com.cakeshop.service.UserService;

/**
 * Servlet implementation class UserRegisterServlet
 */
@WebServlet(name = "UserRegisterServlet", value = "/user_register")
public class UserRegisterServlet extends HttpServlet {
	
	private UserService uService = new UserService();

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user = new User();
		String session_key = (String) request.getSession().getAttribute("KAPTCHA_SESSION_KEY");
		request.getSession().removeAttribute("KAPTCHA_SESSION_KEY");
		String code = request.getParameter("code");
		try {
			BeanUtils.copyProperties(user, request.getParameterMap());
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		if (session_key != null && session_key.equals(code)){
			if(uService.register(user)) {
				request.setAttribute("msg", "注册成功，请登录！");
				request.getRequestDispatcher("user_login.jsp").forward(request, response);
			}else {
				request.setAttribute("msg", "用户名或邮箱重复，请重新填写！");
				request.getRequestDispatcher("user_register.jsp").forward(request, response);
			}
		}else {
			response.getWriter().write("请不要重复提交！！！");
		}

	}
}
